Page({
  data: {
    messages: [],
    inputMsg: '',
    connected: false,
    loading: false,
    scrollTop: 0
  },

  onLoad() {
    this.connectWebSocket();
  },

  connectWebSocket() {
    const socket = wx.connectSocket({
      // url: 'ws://localhost:8080' // 开发环境使用本地地址
      url: "wss://wss.lke.cloud.tencent.com/v1/qbot/chat/conn/?EIO=4&transport=websocket",
    });

    socket.onOpen(() => {
      this.setData({ connected: true });
      wx.showToast({ title: '已连接', icon: 'success' });
    });

    socket.onMessage((res) => {
      this.pushMessage('ai', res.data);
      this.setData({ loading: false });
    });

    socket.onClose(() => {
      this.setData({ connected: false });
      wx.showToast({ title: '连接已关闭', icon: 'none' });
    });

    socket.onError((err) => {
      console.error('WebSocket错误:', err);
      wx.showToast({ title: '连接异常', icon: 'none' });
    });

    this.socket = socket;
  },

  onInput(e) {
    debugger
    this.setData({ inputMsg: e.detail.value });
  },

  sendMessage() {
    if (this.data.loading) return;
    const msg = this.data.inputMsg.trim();
    debugger
    if (!msg) return;
    this.setData({ loading: true });
    this.pushMessage('user', msg);
    
    this.socket.send({
      data: msg,
      success: () => this.setData({ inputMsg: '' }),
      fail: (err) => {
        console.error('发送失败:', err);
        wx.showToast({ title: '发送失败', icon: 'none' });
        this.setData({ loading: false });
      }
    });
  },

  pushMessage(role, content) {
    const newMsg = { role, content, id: Date.now() };
    this.setData({
      messages: [...this.data.messages, newMsg],
      scrollTop: this.data.messages.length * 1000
    });
  }
});
